package com.wsc.personalblog.security;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.wsc.personalblog.common.Constant;
import com.wsc.personalblog.entity.User;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 封装用户信息跟权限信息的UserDetails对象
 */
@JsonIgnoreProperties(ignoreUnknown = true)
public class SecurityUser  implements UserDetails,Serializable {
    private static final long serialVersionUID = 1L;
    // 原始的 User 对象，包含 User 对象的全部属性
    private User user;

    private List<String> permissions;

    @JsonIgnore
    private List<GrantedAuthority> authorities;
    public SecurityUser() {
        // 默认构造函数
    }
    public SecurityUser(User user, List<String> permissions) {
        this.permissions =permissions;
        this.user = user;
    }
    // 对外提供的获取原始 user 对象的 getXxx()方法
    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void setPermissions(List<String> permissions) {
        this.permissions = permissions;
    }

    public List<String> getPermissions() {
        return permissions;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if(authorities != null) return this.authorities;
        // 保存权限信息到authorities;
        if(permissions == null) return null;
        this.authorities = permissions.stream().map((roleStr)-> new SimpleGrantedAuthority(Constant.ROLE_PREFIX+roleStr)).collect(Collectors.toList());
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
